package com.ttbj.product.salesman.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.ttbj.api.dto.CompanyDto;
import com.ttbj.api.dto.Page;
import com.ttbj.api.dto.RoleDto;
import com.ttbj.api.dto.Salesman2;
import com.ttbj.api.dto.SalesmanDto;
import com.ttbj.api.exception.BusinessException;
import com.ttbj.api.salesman.SalesmanService;
import com.ttbj.company.bean.po.Company;
import com.ttbj.constant.Const;
import com.ttbj.constant.PlatFormErrorCode;
import com.ttbj.constant.SalesmanEnum;
import com.ttbj.constant.annotation.SystemServiceLog;
import com.ttbj.core.util.DtoTransitionUtils;
import com.ttbj.core.util.TokenUtils;
import com.ttbj.salesman.bean.po.Salesman;
import com.ttbj.salesman.dao.SalesmanMapper;


@Service("salesmanService")
public class SalesmanServiceImpl implements SalesmanService {
	
	@Autowired
	private SalesmanMapper salesmanMapper;
	
	
	@Override
	public SalesmanDto login(String userName, String password) throws BusinessException {
		Salesman salesman = this.salesmanMapper.selectSalesmanByName(userName, Integer.valueOf(SalesmanEnum.NOT_DELETE.getCode()));
		if (null == salesman) {
			throw new BusinessException("用户名或密码错误", PlatFormErrorCode.OBJECT_DOES_NOT_EXIST.code());
		}
		//加盐后的密码
		String pwd = (new SimpleHash(Const.algorithmName, password, userName, Const.hashIterations)).toString();
		if (!StringUtils.equals(pwd, salesman.getSalesmanPwd())) {
			throw new BusinessException("用户名或密码错误", PlatFormErrorCode.USERNAME_OR_PASSWORD_ERROR.code());
		}
		SalesmanDto salesmanDto = (SalesmanDto) DtoTransitionUtils.trans(SalesmanDto.class, salesman);
		RoleDto roleDto = (RoleDto) DtoTransitionUtils.trans(RoleDto.class, salesman.getRole());
//		CompanyDto companyDto = (CompanyDto) DtoTransitionUtils.trans(CompanyDto.class, salesman.getCompany());
		salesmanDto.setRoleDto(roleDto);
//		salesmanDto.setCompanyDto(companyDto);
		return salesmanDto;
	}

	@Override
	@SystemServiceLog(description="登录前查询用户信息")
	public SalesmanDto findRoleNameByName(String userName) throws BusinessException {
		Salesman salesman = this.salesmanMapper.selectSalesmanByName(userName, SalesmanEnum.NOT_DELETE.getCode());
		if (null == salesman) {
			throw new BusinessException(PlatFormErrorCode.OBJECT_DOES_NOT_EXIST.code());
		}
		SalesmanDto salesmanDto = (SalesmanDto) DtoTransitionUtils.trans(SalesmanDto.class, salesman);
		salesmanDto.setRoleDto((RoleDto) DtoTransitionUtils.trans(RoleDto.class, salesman.getRole()));
		return salesmanDto;
	}
	
	@Override
	public List<SalesmanDto> findAllSalesmanByPage(Page page, SalesmanDto salesmanDto) throws BusinessException {
		Salesman salesman = (Salesman) DtoTransitionUtils.trans(Salesman.class, salesmanDto);
		//如果获取到的公司有信息，说明在使用公司名的条件查询
		if (salesmanDto.getCompanyDto() !=null) {
			Company company = (Company) DtoTransitionUtils.trans(Company.class, salesmanDto.getCompanyDto());
			salesman.setCompany(company);
		}
        List<SalesmanDto> salesmanList = new ArrayList<SalesmanDto>();
        List<Salesman> salesmans = this.salesmanMapper.queryAllSalesmanByPage(page, salesman);
        if (null != salesmans && !salesmans.isEmpty()) {
            for (Salesman man : salesmans) {
                SalesmanDto salesmdto = (SalesmanDto) DtoTransitionUtils.trans(SalesmanDto.class, man);
                if(man.getRole() != null) {
                    salesmdto.setRoleDto((RoleDto) DtoTransitionUtils.trans(RoleDto.class, man.getRole()));
                }
                if (man.getCompany() != null) {
					salesmdto.setCompanyDto((CompanyDto) DtoTransitionUtils.trans(CompanyDto.class, man.getCompany()));
				}
                salesmanList.add(salesmdto);
            }
        }
        return salesmanList;
	}
	
	@Override
	public Integer findAllSalesmanByPageCount(SalesmanDto salesmanDto) throws BusinessException {
		Salesman salesman = (Salesman) DtoTransitionUtils.trans(Salesman.class, salesmanDto);
		//如果获取到的公司有信息，说明在使用公司名的条件查询
		if (salesmanDto.getCompanyDto() !=null) {
			Company company = (Company) DtoTransitionUtils.trans(Company.class, salesmanDto.getCompanyDto());
			salesman.setCompany(company);
		}
		Integer count = this.salesmanMapper.queryAllSalesmanByPageCount(salesman);
		return count;
	}

	@Override
	public SalesmanDto querySalesmanById(Long id) throws BusinessException {
		Salesman salesman = this.salesmanMapper.querySalesmanById(id);
		SalesmanDto salesmanDto = (SalesmanDto) DtoTransitionUtils.trans(SalesmanDto.class, salesman);
		if (salesman.getCompany() != null ) {
			CompanyDto companyDto = (CompanyDto) DtoTransitionUtils.trans(CompanyDto.class, salesman.getCompany());
			salesmanDto.setCompanyDto(companyDto);
		}
		return salesmanDto;
	}

	@Override
	@Transactional
	@SystemServiceLog(description="禁用或启用用户状态")
	public void deleSalesmanById(Long salesmanId, Integer isDel) throws BusinessException {
		if (null == salesmanId || null == isDel) {
			throw new BusinessException("数据有错误！", PlatFormErrorCode.PARAM_IS_NULL.code());
		}
		this.salesmanMapper.deleteSalesmanById(salesmanId, isDel);
	}

	@Override
	@Transactional
	@SystemServiceLog(description="修改用户信息")
	public void editSalesmanInfo(SalesmanDto salesmanDto) throws BusinessException {
		if (null == salesmanDto) {
			throw new BusinessException("数据有错误！", PlatFormErrorCode.OBJECT_DOES_NOT_EXIST.code());
		}
		Salesman salesman = (Salesman) DtoTransitionUtils.trans(Salesman.class, salesmanDto);
		//获取用户名
		String salesmanName = salesmanDto.getSalesmanName();
		//获取密码
		String pwd = salesman.getSalesmanPwd();
		if(StringUtils.isNotBlank(pwd)) {
			//加盐后的密码
			String hashInterationsPwd = (new SimpleHash(Const.algorithmName, pwd, salesmanName, Const.hashIterations)).toString();
			salesman.setSalesmanPwd(hashInterationsPwd);
		}
		//设置更新时间
		salesman.setSalesmanUpdateTime(new Date());
		this.salesmanMapper.updateSalesmanById(salesman);
	}

	@Override
	@Transactional
	@SystemServiceLog(description="增加用户")
	public void addSalesman(SalesmanDto salesmanDto) throws BusinessException {
		if (null == salesmanDto) {
			throw new BusinessException("数据有错误！", PlatFormErrorCode.OBJECT_DOES_NOT_EXIST.code());
		}
		Salesman salesman = (Salesman) DtoTransitionUtils.trans(Salesman.class, salesmanDto);
		//获取用户名
		String salesmanName = salesmanDto.getSalesmanName();
		//通过用户名查询用户数量
		Integer count = this.salesmanMapper.querySalesmanCountByName(salesmanName);
		//如果用户数量大于0，则说明已存在
		if (count > 0) {
			throw new BusinessException("此用户名已被使用", PlatFormErrorCode.DATA_REPEAT.code());
		}
		String pwd = salesman.getSalesmanPwd();
		//如果密码没有输入，则设置默认密码
		if (StringUtils.isBlank(pwd)) {
			pwd = "888888";
		}
		//加盐后的密码
		String hashInterationsPwd = (new SimpleHash(Const.algorithmName, pwd, salesmanName, Const.hashIterations)).toString();
		salesman.setSalesmanPwd(hashInterationsPwd);
		//设置业务员编号
//		salesman.setSalesmanNum(TokenUtils.getNo(GenerateNumConstants.SALESMAN));
		//设置插入时间
		salesman.setSalesmanInsTime(new Date());
		this.salesmanMapper.insertSalesman(salesman);
	}

	@Override
	public int findSalesmanByName(String salesmanName) throws BusinessException {
		int count = this.salesmanMapper.querySalesmanCountByName(salesmanName);
		return count;
	}

	@Override
	public void editSalesmanPwd(String inputSalesmanPwd, String oldSalesmanPwd, String salesmanName, Long salesmanId, String newSalesmanPwd) throws BusinessException {
		if (StringUtils.isBlank(inputSalesmanPwd) || StringUtils.isBlank(newSalesmanPwd)) {
			throw new BusinessException("请输入旧密码和新密码！", PlatFormErrorCode.PARAM_IS_NULL.code());
		}
		//输入旧密码加盐后跟数据库中的密码进行比对
		String HashInterationsPwd = (new SimpleHash(Const.algorithmName, inputSalesmanPwd, salesmanName, Const.hashIterations)).toString();
		if (!oldSalesmanPwd.equals(HashInterationsPwd)) {
			throw new BusinessException("输入的旧密码有误！", PlatFormErrorCode.DATA_SECURITY.code());
		}
		//比对成功后，新密码进行加盐
		String newHashInterationsPwd = (new SimpleHash(Const.algorithmName, newSalesmanPwd, salesmanName, Const.hashIterations)).toString();
		int result = this.salesmanMapper.updateSalesmanPwd(newHashInterationsPwd, salesmanId);
		if (result == 0) {
			throw new BusinessException("密码修改失败！", PlatFormErrorCode.DATA_SECURITY.code());
		}
	}

	@Override
	public List<Salesman2> findIdAndNameById(Long sId, Long eId) {
		List<Salesman2> salesman2s = this.salesmanMapper.queryIdAndNameById(sId, eId);
		return salesman2s;
	}
	
	@Override
	public List<SalesmanDto> findSalesmanIdNameCompany() throws BusinessException {
		List<Salesman> salesmans = this.salesmanMapper.querySalesmanIdNameCompany(SalesmanEnum.NOT_DELETE.getCode(),1);
		List<SalesmanDto> salesmanDtos = new ArrayList<>();
		for (Salesman salesman : salesmans) {
			SalesmanDto salesmanDto = (SalesmanDto) DtoTransitionUtils.trans(SalesmanDto.class, salesman);
			salesmanDtos.add(salesmanDto);
		}
		return salesmanDtos;
	}
}
